package top.suyarong.ftbqsync.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class FormatUtil {

    private FormatUtil() {
    }

    private static volatile FormatUtil instance;

    public static synchronized FormatUtil getInstance() {
        if (instance == null) {
            synchronized (FormatUtil.class) {
                if (instance == null) {
                    instance = new FormatUtil();
                }
            }
        }
        return instance;
    }

    private static final DecimalFormat decimalFormat = new DecimalFormat("#.#");

    public String formatPlaceMessage(String message, Object... args) {
        if (args == null || args.length == 0) {
            return message;
        }
        if (message == null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        int i = 0;
        int j = 0;
        int len = message.length();
        while (i < len) {
            int k = message.indexOf('{', i);
            if (k < 0) {
                result.append(message.substring(i));
                break;
            }
            int l = message.indexOf('}', k + 1);
            if (l < 0) {
                result.append(message.substring(i));
                break;
            }
            if (k > i) {
                result.append(message, i, k);
            }
            if (l == k + 1) {
                if (j >= args.length) {
                    result.append("{}");
                } else {
                    result.append(args[j]);
                }
                j++;
            } else {
                int index = Integer.parseInt(message.substring(k + 1, l));
                if (index >= args.length) {
                    result.append("{}");
                } else {
                    result.append(args[index]);
                }
                j = Math.max(index + 1, j);
            }
            i = l + 1;
        }
        return result.toString();
    }

    public String formatColor(String str) {
        return str.replace("&", "§");
    }

    /**
     * RGB替换
     * 1.16以下暂时不用该方法
     *

    public String formatRGB(String text) {
        Pattern pattern = Pattern.compile("(&#([0-9a-fA-F]{6}))+");
        Matcher matcher = pattern.matcher(text);
        StringBuffer buffer = new StringBuffer();

        while (matcher.find()) {
            String rgb = matcher.group(1);
            String colorCode = ChatColor.of(rgb.substring(1)).toString();
            matcher.appendReplacement(buffer, colorCode);
        }

        matcher.appendTail(buffer);
        return buffer.toString();
    }
    */

    public List<String> formatColor(List<String> str) {
        List<String> replaced = new ArrayList<>();
        for (String s : str) {
            replaced.add(s.replace("&", "§"));
        }
        return replaced;
    }

    public String formatDec(double num) {
        return decimalFormat.format(num);
    }

}
